package org.xhy.quickstarter.authority.aop;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.xhy.quickstarter.authority.BaseAuthorityService;
import org.xhy.quickstarter.authority.annotation.Authority;
import org.xhy.quickstarter.authority.utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Author: Xhy
 * CreateTime: 2022-06-05 00:36
 */
@Aspect
@Component
public class AuthorityAop {


    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpServletResponse response;

    @Autowired
    BaseAuthorityService baseAuthorityService;

    /**
     * 自定义校验aop
     * @param joinPoint
     * @param authority
     * @return
     * @throws Throwable
     */
    @Around("@annotation(authority)")
    public Object authority(ProceedingJoinPoint joinPoint, Authority authority) throws Throwable {

        final String value = authority.value();
        final Boolean result = baseAuthorityService.process(JwtUtils.getUserId(request),value);
        if (!result){
            response.sendError(403);
        }

        Object o = joinPoint.proceed();
        return o;
    }


}
